package com.oro.backingbeans;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import javax.faces.model.SelectItem;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.oro.domain.Categoria;
import com.oro.domain.Scuola;
import com.oro.domain.Studente;
import com.oro.service.StudentService;

public class SearchStudentBean implements Serializable, ActionListener {

	private static final Logger logger = Logger
			.getLogger(SearchStudentBean.class);

	/**
	 * 
	 */
	private static final long serialVersionUID = 669686888756772300L;

	private List<Categoria> categories;

	private List<SelectItem> categoryOptions;
	private Long courseCategoryId;
	private String courseCategoryName;
	private String email;
	private String firstName;
	private Long schoolId; // if selectitem accepts <Long, String>
	private String schoolName;
	private List<SelectItem> schoolOptions;

	private List<Scuola> schools;
	private List<Studente> searchStudentResult;
	private boolean showResults; // the 'rendered' attribute of the result table
	private List<String> studentEmails;
	private List<String> studentNames;
	@Autowired
	StudentService studentService;
	private List<String> studentSurnames;
	private String studentTown;
	private String surname;

	private List<SelectItem> townOptions;
	private List<String> townsIt;

	public SearchStudentBean() {
	}

	public List<String> completeStudentEmail(String query) {
		List<String> results = new ArrayList<String>();
		int max = 10;
		int j = 0;
		String temp;
		while (results.size() < max && j < studentEmails.size()) {
			temp = studentEmails.get(j++);
			if (temp.startsWith(query)) {
				results.add(temp);
			}
		}
		return results;
	}

	public List<String> completeStudentName(String query) {
		List<String> results = new ArrayList<String>();
		int max = 10;
		int j = 0;
		String temp;
		while (results.size() < max && j < studentNames.size()) {
			temp = studentNames.get(j++);
			if (temp.startsWith(query)) {
				results.add(temp);
			}
		}
		return results;
	}

	public List<String> completeStudentSurname(String query) {
		List<String> results = new ArrayList<String>();
		int max = 10;
		int j = 0;
		String temp;
		while (results.size() < max && j < studentSurnames.size()) {
			temp = studentSurnames.get(j++);
			if (temp.startsWith(query)) {
				results.add(temp);
			}
		}
		return results;
	}

	public List<Categoria> getCategories() {
		return categories;
	}

	public List<SelectItem> getCategoryOptions() {
		if (schoolId == null || schoolId == 0L) {
			categoryOptions = new ArrayList<SelectItem>();
			setCategories(studentService.getCategories());
			categoryOptions.add(new SelectItem(null, ""));
			for (Categoria c : categories) {
				categoryOptions.add(new SelectItem(c.getId(), c.getName()));
			}
		} else {
			// Generate the category options for search_by_service SOM
			categoryOptions = new ArrayList<SelectItem>();
			setCategories(studentService.getCategoriesBySchool(schoolId));
			categoryOptions.add(new SelectItem(null, ""));
			for (Categoria c : categories) {
				categoryOptions.add(new SelectItem(c.getId(), c.getName()));
			}
		}
		return categoryOptions;
	}

	public Long getCourseCategoryId() {
		return courseCategoryId;
	}

	public String getCourseCategoryName() {
		return courseCategoryName;
	}

	public String getEmail() {
		return email;
	}

	public String getFirstName() {
		return firstName;
	}

	public Logger getLogger() {
		return logger;
	}

	public Long getSchoolId() {
		return schoolId;
	}

	public String getSchoolName() {
		return schoolName;
	}

	public List<SelectItem> getSchoolOptions() {
		schoolOptions = new ArrayList<SelectItem>();
		setSchools(studentService.getSchools());
		schoolOptions.add(new SelectItem(null, ""));
		for (Scuola s : schools) {
			if (s != null)
				schoolOptions.add(new SelectItem(s.getId(), s
						.getRagioneSociale()));
		}
		return schoolOptions;
	}

	public List<Scuola> getSchools() {
		return schools;
	}

	public List<Studente> getSearchStudentResult() {
		return searchStudentResult;
	}

	public List<String> getStudentEmails() {
		return studentEmails;
	}

	public List<String> getStudentNames() {
		return studentNames;
	}

	public StudentService getStudentService() {
		return studentService;
	}

	public List<String> getStudentSurnames() {
		return studentSurnames;
	}

	public String getStudentTown() {
		return studentTown;
	}

	public String getSurname() {
		return surname;
	}

	public List<SelectItem> getTownOptions() {
		townOptions = new ArrayList<SelectItem>();
		setTownsIt(studentService.getTownsIt());
		townOptions.add(new SelectItem("", ""));
		for (String s : townsIt) {
			if (s != null && s != "")
				townOptions.add(new SelectItem(s, s));
		}
		return townOptions;
	}

	public List<String> getTownsIt() {
		return townsIt;
	}

	public boolean isShowResults() {
		return showResults;
	}

	@PostConstruct
	public void postConstruct() {
		searchStudentResult = new ArrayList<Studente>();
		studentNames = new ArrayList<String>();

		// Generate the list of student names for autocomplete
		studentNames = studentService.getStudentsNames();
		// Generate the list of student surnames for autocomplete
		studentSurnames = studentService.getStudentsSurnames();
		// Generate the list of student emails for autocomplete
		setStudentEmails(studentService.getStudentsEmails());

		searchStudentResult = new ArrayList<Studente>();

		getLogger().info("SearchStudentBean has been constructed.");
	}

	@PreDestroy
	public void preDestroy() {
		getLogger().info("SearchStudentBean is being destroyed.");
	}

	@Override
	public void processAction(ActionEvent e) throws AbortProcessingException {
		if (e.getComponent().getId().equals("searchMenuitem")) {
			reset();
		}
	}

	public void reset() {
		firstName = null;
		surname = null;
		email = null;
		studentTown = null;
		schoolId = 0L;
		courseCategoryId = 0L;
		searchStudentResult = new ArrayList<Studente>();
	}

	public void setCategories(List<Categoria> categories) {
		this.categories = categories;
	}

	public void setCategoryOptions(List<SelectItem> categoryOptions) {
		this.categoryOptions = categoryOptions;
	}

	public void setCourseCategoryId(Long courseCategoryId) {
		this.courseCategoryId = courseCategoryId;
	}

	public void setCourseCategoryName(String courseCategoryName) {
		this.courseCategoryName = courseCategoryName;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public void setSchoolId(Long schoolId) {
		this.schoolId = schoolId;
	}

	public void setSchoolName(String schoolName) {
		this.schoolName = schoolName;
	}

	public void setSchoolOptions(List<SelectItem> schoolOptions) {
		this.schoolOptions = schoolOptions;
	}

	public void setSchools(List<Scuola> schools) {
		this.schools = schools;
	}

	public void setSearchStudentResult(List<Studente> searchStudentResult) {
		this.searchStudentResult = searchStudentResult;
	}

	public void setShowResults(boolean showResults) {
		this.showResults = showResults;
	}

	public void setStudentEmails(List<String> studentEmails) {
		this.studentEmails = studentEmails;
	}

	public void setStudentNames(List<String> studentNames) {
		this.studentNames = studentNames;
	}

	public void setStudentService(StudentService studentService) {
		this.studentService = studentService;
	}

	public void setStudentSurnames(List<String> studentSurnames) {
		this.studentSurnames = studentSurnames;
	}

	public void setStudentTown(String studentTown) {
		this.studentTown = studentTown;
	}

	public void setSurname(String surname) {
		this.surname = surname;
	}

	public void setTownOptions(List<SelectItem> townOptions) {
		this.townOptions = townOptions;
	}

	public void setTownsIt(List<String> townsIt) {
		this.townsIt = townsIt;
	}

	public void studentTownChanged() {
		// we have to regenerate the list of names and the list of surnames and
		// the list of emails
		// We need the student names and surnames of the given town.

		if (studentTown != null && studentTown != "") {
			studentNames = studentService.getStudentsNamesByTown(studentTown);
			studentSurnames = studentService
					.getStudentsSurnamesByTown(studentTown);
			studentEmails = studentService.getStudentsEmailsByTown(studentTown);
		} else {
			studentNames = studentService.getStudentsNames();
			studentSurnames = studentService.getStudentsSurnames();
			studentEmails = studentService.getStudentsEmails();
		}
	}

	public List<Studente> submit() {
		searchStudentResult = studentService.searchStudents(firstName, surname,
				email, studentTown, schoolId, courseCategoryId);

		firstName = null;
		surname = null;
		email = null;
		studentTown = null;
		schoolId = 0L;
		courseCategoryId = 0L;

		return searchStudentResult;
	}

}
